<?php
/**
 * Created by PhpStorm.
 * User: yui
 * Date: 2017/4/7
 * Time: 20:10
 */

namespace backend\controllers;

use common\controllers\BackendCommonCtrl;
use Yii;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\services\UserSve;
use yii\web\Response;
use yii\helpers\Url;

class HomeController extends BackendCommonCtrl
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index', 'get-image-json'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
//                    'logout' => ['post'],
                ],
            ],
        ];
    }

    public function actionError()
    {
        $exception = Yii::$app->errorHandler->exception;
        if ($exception !== null) {
            return $this->render('error', ['exception' => $exception]);
        }
    }
    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionIndex()
    {
        \common\services\MenuSve::getUserMenus();
        return $this->render('index');
    }


    /**
     * 登录
     * @return string|\yii\web\Response
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }
        if (Yii::$app->request->isPost) {
            $User = new UserSve();
            $rs = $User->login(Yii::$app->request->post());
            if ($rs['code'] === 0) {
                $rs['redirect'] = Url::toRoute('home/index');
            }
            return $this->asJson($rs);
        } else {
            $this->layout = 'main-login';
            return $this->render('login');
        }
    }

    /**
     * 注销
     * @return Response
     */
    public function actionLogout()
    {
        $User = new UserSve();
        $rs = $User->logout();
        if ($rs['code'] === 0) {
            return $this->redirect('/home/login');
        } else {
            die($rs['msg']);
        }
    }
}